
<template>
  <div class="login">
    <div class="login-con">
      <img src="../../assets/images/logo.png" alt="" class="logoImg" />
      <div class="form-con">
        <p class="logoText">登录</p>
        <login-form @on-success-valid="handleSubmit"></login-form>
      </div>
    </div>
  </div>
</template>

<script>
import LoginForm from '_c/login-form'
import { mapActions } from 'vuex'
import { login, getMenuList } from '@/api/login.js'
export default {
  components: {
    LoginForm
  },
  mounted () {},
  methods: {
    ...mapActions(['handleLogin', 'getUserInfo', 'postuser']),
    handleSubmit ({ userName, pwd, remember }) {
      let that = this
      login({ userName, pwd }).then((res) => {
        if (res.status === 200) {
          if (res.data.user) {
            that.$Message.success('登录成功！正在进入页面中')
            localStorage.setItem('userInfo', JSON.stringify(res.data))

            getMenuList().then(response => {
              const menuList = this.getMenu(response.data)
              localStorage.setItem('menuList', JSON.stringify(menuList))
            }).then(() => {
              that.postuser().then(res => {
                that.$router.push({
                  name: that.$config.homeName
                })
              })
            })
          } else {
            that.$Message.warning('登录失败')
          }
        } else {
          that.$Message.warning('用户名或密码错误！')
        }
      })
    },
    getMenu (data) {
      let menu = JSON.parse(localStorage.getItem('userInfo')).functions
      let list = []
      let map = {}
      data.forEach(item => {
        item.name = item.url || item.id
        item.href = item.url || item.id
        item.meta = {
          title: item.functionName
        }
        map[item.id] = item
      })
      menu.forEach(item => {
        let parent = map[item.parentID]
        let current = map[item.id]
        item.name = current.url || current.id
        item.href = current.url || current.id
        item.meta = {
          title: current.functionName
        }

        if (parent) {
          if (!parent.children) {
            parent.children = []
          }
          parent.children.push(item)
          let isHas = list.find(row => row.id === parent.id)
          if (!isHas) {
            list.push(parent)
          }
        } else {
          list.push(item)
        }
      })
      return list
    }

  }
}
</script>
<style lang="less">
@import "./login.less";
</style>
<style>
</style>
